var Content = React.createClass({
	render: function () {
		return (
			<Versions />
		)
	}
});
// 合作商列表
var partnerList = [
	{
		partner_id: 0,
		name: 'IDO'
	},
	{
		partner_id: 1,
		name: '大金空调'
	},
	{
		partner_id: 2,
		name: '彩虹'
	},
	{
		partner_id: 3,
		name: '微软'
	},
	{
		partner_id: 4,
		name: 'Navidia'
	},
	{
		partner_id: 5,
		name: 'Google'
	}

];

// 版本列表
var partnerVersions = [
	{
		id: 0,
		partner_id: 10,
		version: "v1.0.201",
		version_code: 10,
		release_notes: "日程智能识别 — 识别重要消息，秒建日程",
		download_url: "http://cdn2.parllay.cn",
		created_date: '2017.6.8'
	},
	{
		id: 1,
		partner_id: 10,
		version: "v1.0.200",
		version_code: 9,
		release_notes: "消息支持撤回 — 消息发错？一键撤回",
		download_url: "http://cdn2.parllay.cn",
		created_date: '2017.6.1'
	},
	{
		id: 2,
		partner_id: 10,
		version: "v1.0.100",
		version_code: 8,
		release_notes: "好友搜索优化 — 更快，更准，更好用",
		download_url: "http://cdn2.parllay.cn",
		created_date: '2017.5.5'
	}


]


//版本管理
class Versions extends React.Component {

	constructor(props) {
		super(props);
		this.state = {
			current: 0,
			partner_id: 0,
			id: '',
			partnerList: [],
			partnerVersions: [],
			temp: [],
			version: '',
			versionCode: '',
			version_code: 0,
			release_notes: '',
			download_url: '',
			showModal: false,
			action: '',
			delId: '',
			uploading: false,
			pageIndex: 1,
			xhr: {}
		}
	}

	//使用AJAX获取所有合作商和第一个合作商的版本列表数据
	componentDidMount() {
		var that = this,
			partner_id = that.state.partner_id,
			pageIndex = this.state.pageIndex;


		$.ajax({
			type: 'GET',
			url: '/partners?pageIndex=' + pageIndex + '&count=5',
			dataType: 'json',
			success: function (data) {
				if (data.success) {
					if(data.data.length > 0){
						var id = data.data[0].id;
						that.setState({
							partner_id: id
						});
						$.ajax({
							type: 'GET',
							url: '/partners/' + id + '/tv_app_versions?pageIndex=' + pageIndex + '&count=5',
							dataType: 'json',
							success: function (data) {
								if (data.success) {
									var d = data.data;
									if (d.length > 0) {
										that.setState({
											temp: d,
											partnerVersions: d,
											version_code: d[0].version_code
										});
									}
								}
							}
						});
						that.setState({
							partnerList: data.data
						});
					}
				}
			}
		});



		this.setState({
			//partnerList: partnerList,
			// partnerVersions: partnerVersions
		});
	}

	// 更改合作商的事件
	changeHandle(e) {
		var id = e.target.id,
			that = this;

		console.log(e.target);
		/*
		请求不通数据源的AJAX方法
		*/
		that.setState({
			partner_id: id,
			current: id - 1,
			partnerVersions: []
		});

		$.ajax({
			type: 'get',
			url: '/partners/' + id + '/tv_app_versions?pageIndex=1&count=5',
			dataType: 'json',
			success: function (data) {
				if (data.success) {
					that.setState({
						temp: data.data,
						partnerVersions: data.data
					});
				} else {

				}
			},
			error: function () {
				console.error(false, '系统错误，请刷新重试!')
			}
		});

	}

	// 添加版本更新
	addVersion(event) {
		event.stopPropagation();
		var partner_id = event.target.id;
		this.setState({
			current: partner_id - 1,
			action: 'add',
			partner_id: partner_id,
			showModal: !this.state.showModal
		});
	}
	// 编辑日志文件
	editVersion(e) {
		var id = e.target.id,
			v = {},
			partnerVersions = this.state.partnerVersions;
		for (var i = 0; i < partnerVersions.length; i++) {
			if (id == partnerVersions[i].id) {
				v = partnerVersions[i];
			}
		}


		this.setState({
			action: 'update',
			id: id,
			showModal: !this.state.showModal,
			version: v.version,
			versionCode: v.version_code,
			release_notes: v.release_notes,
			download_url: v.download_url

		});

	}

	//版本号和更新内容事件处理
	contentHandle(e) {
		var id = e.target.id,
			val = e.target.value;
		switch (id) {
			case 'version':
				this.setState({
					version: val
				});
				break;
			case 'versionCode':
				this.setState({
					versionCode: val
				});
				break;
			case 'release_notes':
				this.setState({
					release_notes: val
				});
				break;
		}
	}

	// 上传APK文件函数
	changeApkFile() {
		var that = this;
		that.setState({
			uploading: !that.state.uploading
		});
		changeAvatarHandle(function (result, xhr) {
			/*
				如果文件不是APK文件则调用七牛进行上传文件
			*/

			if (result != '') {
				var file_url = 'http://cdn.ifenghuotai.cn/' + JSON.parse(result).key;
				that.setState({
					download_url: file_url
				});
			}

			that.setState({
				xhr: xhr,
				uploading: false
			});
		});

	}

	// 取消添加日志信息
	cancelHandle() {
		/*
			取消上传文件终端上传
		*/
		xhr.abort();

		this.setState({
			uploading: false,
			version: '',
			versionCode: '',
			release_notes: '',
			download_url: '',
			showModal: !this.state.showModal
		});
	}

	// 确定创建或者修改版本日志信息
	confirmHandle() {
		var that = this,
			url = '',
			partner_id = this.state.partner_id,
			id = this.state.id,
			version = this.state.version,
			version_code = this.state.version_code + 1,
			release_notes = this.state.release_notes,
			download_url = this.state.download_url,
			action = this.state.action,
			data = {};


		if (action == 'add') {
			url = '/partners/' + partner_id + '/tv_app_versions';
			data = {
				partner_id: partner_id,
				version_code: version_code,
				version: version,
				release_notes: release_notes,
				download_url: download_url
			};

		} else {
			url = '/partners/' + partner_id + '/tv_app_versions/' + id;
			data = {
				partner_id: partner_id,
				version_code: version_code,
				version: version,
				release_notes: release_notes,
				download_url: download_url
			}
		}


		$.ajax({
			type: 'POST',
			url: url,
			dataType: 'json',
			data: data,
			success: function (data) {

				var tip = document.getElementById('tip'),
					box_title = tip.querySelector('.modal-title'),
					box_body = tip.querySelector('.modal-body'),
					text = '';
				if (data.success) {
					text = '保存成功!';

					/*
						再次请求后台拿到当前合作商的所有版本数据
					*/
					$.ajax({
						type: 'GET',
						url: '/partners/' + partner_id + '/tv_app_versions?pageIndex=1&count=5',
						dataType: 'json',
						success: function (data) {
							if (data.success) {
								that.setState({
									version_code: data.data[0].version_code,
									partnerVersions: data.data
								});
							}
						}
					});


				} else {
					text = data.error;

				}
				box_title.innerText = '结果';
				box_body.innerText = text;
				tip.style.display = 'block';
				setTimeout(function () {
					tip.className = 'modal fade in';
				}, 100);
				setTimeout(function () {
					tip.className = 'modal fade';
					setTimeout(function () {
						tip.style.display = 'none';
					}, 100);
				}, 2000);
			},
			error: function () {
				console.log(false, '内部错误，请稍后再试!')
			}
		});
		this.setState({
			version: '',
			versionCode: '',
			release_notes: '',
			download_url: '',
			showModal: !this.state.showModal
		});


	}


	// 分页逻辑
	changePageHandle(e) {
		var that = this,
			partnerVersions = that.state.partnerVersions,
			type = e.target.type,
			url = '',
			partner_id = this.state.partner_id,
			pageIndex = this.state.pageIndex + 1,
			url = '/partners/' + partner_id + '/tv_app_versions?pageIndex=' + pageIndex + '&count=5';


		$.ajax({
			type: 'GET',
			url: url,
			dataType: 'json',
			success: function (data) {
				if (data.success) {
					var temp = data.data;
					if (temp.length > 0) {
						that.setState({
							partnerVersions: partnerVersions.concat(temp)
						});
					}
					that.setState({
						temp: temp
					});
				}
			}
		});
	}


	render() {
		var current = this.state.current,
			partner_id = this.state.partner_id,
			showModal = this.state.showModal,
			partnerList = this.state.partnerList,
			partnerVersions = this.state.partnerVersions,
			temp = this.state.temp,
			contentHandle = this.contentHandle.bind(this),
			changeApkFile = this.changeApkFile.bind(this),
			cancelHandle = this.cancelHandle.bind(this),
			confirmHandle = this.confirmHandle.bind(this),
			version = this.state.version,
			versionCode = this.state.versionCode,
			release_notes = this.state.release_notes,
			download_url = this.state.download_url,
			addVersion = this.addVersion.bind(this),
			editVersion = this.editVersion.bind(this),
			action = this.state.action,
			title = '',
			uploading = this.state.uploading,
			pageIndex = this.state.pageIndex,
			changePageHandle = this.changePageHandle.bind(this);


		if (action == 'add') {
			title = '添加版本更新';
		} else {
			title = '修改版本更新'
		}

		var args = {
			title: title,
			uploading: uploading,
			showModal: showModal,
			contentHandle: contentHandle,
			changeApkFile: changeApkFile,
			cancelHandle: cancelHandle,
			confirmHandle: confirmHandle,
			version: version,
			versionCode: versionCode,
			release_notes: release_notes,
			download_url: download_url
		}
		

		return (
			<div className="versions">
				{
					partnerList.length > 0 ?
						<div className="row">
							<div className="col-sm-3">
								<div className="box box-solid">

									<div className="box-header with-border">
										<i className="fa fa-users"></i>
										<h3 className="box-title">合作商</h3>
										{/*{
											this.state.isCreate ?
												<button type="button" className="btn btn-primary btn-sm pull-right" onClick={this.addPartner.bind(this)}>取消</button>
												:
												<button className="btn btn-primary btn-sm pull-right" type="button" onClick={this.addPartner.bind(this)}><i className="fa fa-plus"></i>添加合作商</button>

										}*/}
									</div>


									<div className="box-body">
										{/*{
											this.state.isCreate ?
												<form className="form-inline">
													<div className="form-group" style={{ 'width': '75%' }}>
														<input title="请输入合作商名称" style={{ 'width': '100%' }} type="text" className="form-control" id="partner_name" value={this.state.partnerName} onChange={this.createPartnerHandle.bind(this)} />
													</div>
													<button id="confirm_add_btn" data-loading-text="..." style={{ 'marginLeft': '10px', 'width': '20%' }} type="button" className="btn btn-primary btn-sm" onClick={this.confirmAddPartner.bind(this)}>确认</button>
												</form>
												: ''
										}*/}

										<ul id="box-ul" onClick={this.changeHandle.bind(this)}>
											{
												partnerList.map((partner, index) => {
													return <li key={index} className={current == index ? "active" : ""} id={partner.id}>
														<span id={partner.id}>{partner.name}</span>
														<button id={partner.id} type="button" className="btn btn-primary btn-xs pull-right hideCss" onClick={addVersion}>添加版本更新</button>
													</li>
												})
											}

										</ul>
									</div>
								</div>
							</div>
							{/*单个版本组件*/}
							<div className="col-sm-9">

								{/*若当前合作商版本日志为空则提示创建版本更新*/}
								{
									partnerVersions.length == 0 ?
										<div className="callout callout-info">
											<h4>数据为空!</h4>
											<p>当前合作商没有版本，<a href="javascript:void(0);" id={partner_id} onClick={addVersion}>创建一个?</a></p>
										</div>

										:
										partnerVersions.map((item, index) => {
											return <Version key={index} index={index} {...item} editVersion={editVersion} />
										})
								}
								{/*如果合作商列表数据大于等于5条则显示加载更多按钮*/}
								{
									partnerVersions.length == 0 ?
										''
										:
										<div className="more">
											{
												temp.length >= 4 ?
													<span onClick={changePageHandle}>加载更多</span>
													:
													<p>没有更多数据了</p>

											}
										</div>

								}
							</div>
						</div>
						:
						<div className="callout callout-info">
							<h4>合作商不存在!</h4>
							<p>现在没有合作商，请新建合作商后刷新页面!</p>
						</div>

				}




				{/*选择文件提示*/}
				<div id="tip" className="modal fade" tabIndex="-1" role="dialog">
					<div className="modal-dialog" role="document">
						<div className="modal-content">
							<div className="modal-header">
								<h4 className="modal-title">错误</h4>
							</div>
							<div className="modal-body">
								<p>选择的文件不是apk文件包，请选择后缀为apk的文件!</p>
							</div>
						</div>
					</div>
				</div>

				{/* 这里是添加版本更新的弹出框 */}
				{
					showModal ?
						<AddVersion  {...args} />
						: ''

				}

			</div>
		);
	}
}



// 单个版本更新组件
class Version extends React.Component {


	render() {

		var lines = this.props.release_notes.split("\n");
		return (

			<div className="box box-solid" >

				<div className="box-header with-border">
					<h3 className="box-title">
						<span>{this.props.version}</span>
						<button id={this.props.id} type="button" className="btn btn-primary btn-sm" onClick={this.props.editVersion}>编辑版本更新内容</button>
						{
							this.props.index == 0 ?
								<small className="label label-danger"><i className="fa fa-clock-o"></i> 当前版本</small>
								: ''

						}
						<span className="pull-right publish-date">{this.props.created_date}</span>
					</h3>
				</div>
				<div className="box-body">
					<dl className="dl-horizontal">
						<dt>更新内容</dt>
						{
							lines.map(line => {
								return <dd>{line}</dd>
							})
						}
					</dl>
					<div className="pull-right">
						<a className="btn btn-app" href={this.props.download_url} target="_blank">
							<i className="fa fa-download"></i> 下载
						</a>
					</div>
				</div>

			</div >


		);
	}
}


// 添加版本更新日志组件
class AddVersion extends React.Component {

	constructor(props) {
		super(props);
		this.state = {
			showModal: false
		}
	}

	componentDidMount() {
		var that = this;
		setTimeout(function () {
			that.setState({
				showModal: !that.state.showModal
			});
		}, 100);

	}



	render() {

		var save = false;
		if (this.props.version && this.props.release_notes && this.props.download_url) {
			save = true;
		}

		return (
			<div className="popup-container">

				<div className={'modal fade ' + (this.state.showModal ? 'in' : '')} tabIndex="-1" role="dialog" style={{ 'display': 'block' }}>
					<div className="modal-dialog" role="document">
						<div className="modal-content">
							<div className="modal-header">
								<button type="button" className="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true" onClick={this.props.cancelHandle}>×</span></button>
								<h4 className="modal-title">{this.props.title}</h4>
							</div>
							<div className="modal-body">
								<form className="form-horizontal">
									<div className="form-group">
										<label htmlFor="version" className="col-sm-3 control-label">版本：</label>

										<div className="col-sm-9">
											<input type="text" className="form-control" id="version" placeholder="请输入版本名称" value={this.props.version} onChange={this.props.contentHandle} />
										</div>
									</div>
									<div className="form-group">
										<label htmlFor="versionCode" className="col-sm-3 control-label">版本号：</label>

										<div className="col-sm-9">
											<input type="text" className="form-control" id="versionCode" placeholder="请输入整数的版本号" value={this.props.versionCode} onChange={this.props.contentHandle} />
										</div>
									</div>
									<div className="form-group">
										<label htmlFor="release_notes" className="col-sm-3 control-label">更新内容：</label>

										<div className="col-sm-9">
											<textarea id="release_notes" className="form-control" rows="5" value={this.props.release_notes} placeholder="更新内容" onChange={this.props.contentHandle}></textarea>
										</div>
									</div>
									<div className="form-group">
										<label htmlFor="sourceCode" className="col-sm-3 control-label">APK 文件路径：</label>

										<div className="col-sm-9">
											<div className="uploadSource">

												<div className="box">
													<div className="box-body">
														{
															this.props.uploading ?
																<div className="overlay">
																	<i className="fa fa-refresh fa-spin"></i>
																</div>
																:
																<div>
																	{
																		this.props.download_url.length > 0 ?
																			<div>
																				<p>{this.props.download_url}</p>
																				<p>
																					<label htmlFor="sourceCode" id="changeLabel" className="changeLabel"><i className="fa fa-exchange" style={{ 'margin': '8px 0 0 85px', 'fontSize': '30px' }}></i></label>
																				</p>
																			</div>
																			:
																			<label htmlFor="sourceCode" id="uploadLabel" className="uploadLabel"></label>
																	}
																</div>

														}

													</div>
												</div>

												<input type="file" className="form-control" id="sourceCode" style={{ 'display': 'none' }} onChange={this.props.changeApkFile} />

											</div>
										</div>
									</div>

								</form>

							</div>
							<div className="modal-footer">
								<button type="button" className="btn btn-default" onClick={this.props.cancelHandle}>取消</button>
								<button type="button" className={save ? 'btn btn-primary' : 'btn btn-primary disabled'} onClick={save ? this.props.confirmHandle : ''}>确认</button>
							</div>
						</div>
					</div>
				</div>

			</div>
		);
	}
}



